package com.wuyan.web.base.helper.auth;

import com.wuyan.web.base.entity.PubConfig;
import com.wuyan.web.base.entity.PubRole;
import com.wuyan.web.base.helper.PubConfigHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户登录账户相关工具类
 */

@Slf4j
@Component
public class LoginInfoHelper {

    @Autowired
    private PubConfigHelper pubConfigHelper;

    /**
     * 获取超管角色ID
     *
     * @return Set<Integer>
     */
    public Set<Integer> getSuperAdminRole() {
        List<PubConfig> config = pubConfigHelper.configs("sys", "role.superAdmin");
        if (null == config || config.size() < 1) return new HashSet<>();
        return config.stream().map(t -> Integer.parseInt(t.getCfgValue())).collect(Collectors.toSet());
    }

    /**
     * 角色存在：判断actual是否存在expect
     *
     * @param expect 期望存在的角色ID
     * @param actual 实际值
     * @return boolean
     */
    public boolean role(Set<Integer> expect, List<PubRole> actual) {
        if (null == actual || actual.size() < 1 || null == expect) return false;
        List<PubRole> list = actual.stream().filter(t -> expect.contains(t.getId())).collect(Collectors.toList());
        boolean res = list.size() > 0;

        // 同步校验超管
        if (!res) {
            Set<Integer> superAdminRole = getSuperAdminRole();
            if (null == superAdminRole || superAdminRole.size() < 1) return false;
            list = actual.stream().filter(t -> superAdminRole.contains(t.getId())).collect(Collectors.toList());
            return list.size() > 0;
        }

        return res;
    }

}
